use std::collections::HashMap;
use std::sync::{Arc, Mutex};

type EventCallback = Arc<dyn Fn() + Send + Sync>;

pub struct EventEmitter {
    _events: Mutex<HashMap<String, Vec<EventCallback>>>,
    _max_listeners: usize,
}

impl EventEmitter {
    /// Creates an EventEmitter instance
    /// # Examples
    /// ```
    /// use std::sync::{Arc};
    /// use EventEmitter::EventEmitter;
    /// 
    /// fn main() {
    ///     let emitter = EventEmitter::new();
    /// 
    ///     let callback1 = Arc::new(|| println!("[event1 emitted]: The first callback of event1 has been called."));
    ///     let callback2 = Arc::new(|| println!("[event1 emitted]: The second callback of event1 has been called."));
    ///     let callback3 = Arc::new(|| println!("[event2 emitted]: The only one callbask of event2 has been called."));
    /// 
    ///     // Add event listener
    ///     emitter.on("event1", callback1);
    ///     emitter.add_listener("event1", callback2); // The `add_listene` method is an alias method for the `on` method.
    ///     emitter.on("event2", callback3);
    /// 
    ///     let ct1 = emitter.listener_count("event1");
    ///     let ct2 = emitter.listener_count("event2");
    ///     println!("Number of Listeners for event1 is: {ct1}, \nNumber of Listeners for event2 is: {ct2}");
    /// 
    ///     emitter.emit("event1"); // Emit event1
    ///     emitter.emit("event2"); // Emit event1
    /// }
    /// ```
    /// 
    pub fn new() -> Self {
        EventEmitter {
            _events: Mutex::new(HashMap::new()),
            _max_listeners: usize::MAX,
        }
    }

    /// 设置最大监听器数量
    /// Set the maximum number of listeners
    pub fn set_max_listeners(&mut self, max_listeners: usize) {
        self._max_listeners = max_listeners;
    }

    /// 获取最大监听器数量
    pub fn get_max_listeners(&self) -> usize {
        self._max_listeners
    }

    /// 添加事件监听器
    /// 
    /// 是 `on` 方法的别名
    /// 
    /// Get the maximum number of listeners
    /// 
    /// alias method for the `on` method.
    pub fn add_listener(&self, event: &str, callback: EventCallback) {
        self.on(event, callback);
    }

    /// 添加事件监听器
    /// Add event listener
    pub fn on(&self, event: &str, callback: EventCallback) {
        let mut events = self._events.lock().unwrap();
        let callbacks = events.entry(event.to_string()).or_insert(Vec::new());
        callbacks.push(callback);
    }

    /// 移除事件监听器
    /// 
    /// 是 `off` 方法的别名
    /// 
    /// Remove the event listener
    /// 
    /// alias method for the `off` method.
    pub fn remove_listener(&self, event: &str, callback: &EventCallback) {
        self.off(event, callback);
    }

    pub fn off(&self, event: &str, callback: &EventCallback) {
        let mut events = self._events.lock().unwrap();
        if let Some(callbacks) = events.get_mut(event) {
            callbacks.retain(|cb| !Arc::ptr_eq(cb, callback));
        }
    }

    /// 添加一次性事件监听器
    /// 
    /// 使用该方法添加的监听器函数将在发布一次事件成功执行后移除。
    /// 
    /// Add a one-time event listener
    /// 
    /// Listener functions added by this method will be removed after publishing an event successfully.
    /// 
    // pub fn once(&self, event: &str, callback: EventCallback) {
    //     let callback_wrapper = Arc::new(move || {
    //         self.off(event, &callback);
    //         (*callback)();
    //     });
    //     self.on(event, callback_wrapper);
    // }

    

    /// 触发事件
    /// 
    /// 触发相当于“发布-订阅”模式中的“发布”，一但某个事件被触发，该事件对应得所有监听器函数都会被执行。监听器就相当于“订阅者”。
    /// 
    /// trigger event
    /// 
    /// Triggering is equivalent to "publish" in "publish-subscribe" mode. Once an event is triggered, all listeners corresponding to the event will be executed. Listeners are equivalent to "subscribers".
    /// 
    pub fn emit(&self, event: &str) {
        let events = self._events.lock().unwrap();
        if let Some(callbacks) = events.get(event) {
            for callback in callbacks {
                let callback_clone = callback.clone();
                // Spawn a new thread to run each callback asynchronously
                std::thread::spawn(move || {
                    (*callback_clone)();
                });
            }
        }
    }

    /// 移除所有事件的所有监听器
    /// Remove all listeners for all events.
    pub fn remove_all_listeners(&self, event: &str) {
        let mut events = self._events.lock().unwrap();
        events.remove(event);
    }

    /// 从指定事件监听器向量的前方插入新的监听器
    /// 
    /// 该方法与使用 `on`、`add_listener` 方法添加新的监听器时，插入监听器向量的方向相反
    /// 
    /// Inserts a new listener from the front of the specified event listener vector.
    /// 
    /// This method is opposite to the direction of inserting the listener vector when adding a new listener by using the' on' and' add_listener' methods.
    pub fn prepend_listener(&self, event: &str, callback: EventCallback) {
        let mut events = self._events.lock().unwrap();
        let callbacks = events.entry(event.to_string()).or_insert(Vec::new());
        callbacks.insert(0, callback);
    }

    // pub fn prepend_once_listener(&self, event: &str, callback: EventCallback) {
    //     let callback_wrapper = Arc::new(move || {
    //         self.off(event, &callback);
    //         (*callback)();
    //     });
    //     self.prepend_listener(event, callback_wrapper);
    // }

    /// 获取指定事件的监听器
    /// 
    /// Gets the listener for the specified event.
    /// 
    pub fn listeners(&self, event: &str) -> Vec<EventCallback> {
        let events = self._events.lock().unwrap();
        if let Some(callbacks) = events.get(event) {
            callbacks.clone()
        } else {
            Vec::new()
        }
    }

    /// 获取指定事件的监听器数量
    /// 
    /// Gets the number of listeners for the specified event.
    pub fn listener_count(&self, event: &str) -> usize {
        let events = self._events.lock().unwrap();
        if let Some(callbacks) = events.get(event) {
            callbacks.len()
        } else {
            0
        }
    }
}